<template>
  <div class="ele-body">
    <a-card :bordered="false">
      <!-- 搜索表单 -->
      <a-form :label-col="{ md: { span: 6 }, sm: { span: 24 } }" :wrapper-col="{ md: { span: 18 }, sm: { span: 24 } }">
        <a-row>
          <a-col :lg="6" :md="12" :sm="24" :xs="24">
            <a-form-item label="名称">
              <a-auto-complete v-model:value="eventsWhere.customer_val" :options="customerOptions" placeholder="请输入"
              @select="customer_onSelect_s" @search="customer_onSearch" :allow-clear="false" />
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24" :xs="24">
            <a-form-item label="事件时间">
              <a-date-picker v-model:value="eventsWhere.eventDate" placeholder="请输入事件时间" valueFormat="YYYY-MM-DD" class="ele-fluid" allow-clear/>
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24" :xs="24" >
            <a-form-item :wrapper-col="{ span: 24 }">
              <em></em>
              <a-space>
                <a-button type="primary" @click="eventsReload">查询</a-button>
                <a-button @click="eventsReset">重置</a-button>
              </a-space>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <!-- 表格 -->
      <ele-pro-table ref="eventsTableRef" row-key="id" :columns="columns" :datasource="datasource" :scroll="{ x: 1000 }">
        <template #toolbar>
          <a-space>
            <a-button type="primary" @click="eventsOpenEdit()" v-any-permission="['order:events:save']">
              <template #icon>
                <plus-outlined />
              </template>
              <span>新建</span>
            </a-button>
          </a-space>
        </template>
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'action'">
            <a-space>
              <a @click="eventsOpenEdit(record)" v-any-permission="['order:events:update']">修改</a>
              <a-divider type="vertical" />
              <a-popconfirm title="确定要删除此项吗？" @confirm="eventsRemove(record)">
                <a class="ele-text-danger" v-any-permission="['order:events:remove']">删除</a>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </ele-pro-table>
    </a-card>
    <!-- 事件记录添加、修改弹窗 -->
    <ele-modal :width="560" v-model:visible="eventsVisible_modal" :confirm-loading="loading" :title="eventsIsUpdate ? '修改事件记录' : '新建事件记录'"
      position="center" :body-style="{ paddingBottom: '8px' }" @ok="eventsSave" :maskClosable="false">
      <a-form ref="eventsFormRef" :model="eventsForm" :rules="eventsRules" :label-col="{ md: { span: 7 }, sm: { span: 24 } }"
        :wrapper-col="{ md: { span: 17 }, sm: { span: 24 } }">
        <a-form-item label="事件时间" name="eventDate">
          <a-date-picker v-model:value="eventsForm.eventDate" placeholder="请输入事件时间" valueFormat="YYYY-MM-DD" class="ele-fluid" allow-clear/>
        </a-form-item>
        <a-form-item label="客户名称" name="customer_val">
          <a-auto-complete v-model:value="eventsForm.customer_val" :options="customerOptions" placeholder="请输入客户名称"
          @select="customer_onSelect" @search="customer_onSearch" @blur="customer_blur" allow-clear />
        </a-form-item>
        <a-form-item label="内容" name="content">
          <a-textarea v-model:value="eventsForm.content" allow-clear :maxlength="1200" placeholder="请输入内容" autocomplete="off" :rows="4"/>
        </a-form-item>
        <a-form-item label="备注" name="remark">
          <a-textarea v-model:value="eventsForm.remark" allow-clear :maxlength="1200" placeholder="请输入备注" autocomplete="off" :rows="4"/>
        </a-form-item>
        <a-form-item label="类型" name="type">
          <a-select v-model:value="eventsForm.type" placeholder="请选择"  allow-clear>
                <a-select-option value="报价">报价</a-select-option>
                <a-select-option value="订单">订单</a-select-option>
              </a-select>
        </a-form-item>
      </a-form>
    </ele-modal>
  </div>
</template>

<script setup>
import { ref, reactive, watch } from 'vue';
import { toDateString } from 'ele-admin-pro';
import useFormData from '@/utils/use-form-data';
import { message } from 'ant-design-vue';
import dayjs from 'dayjs';
import { TIME_OUT } from '@/config/damon';

import { pageEvents, removeEvents, addEvents, updateEvents } from '@/api/order/events';
import { listCustomersSel } from '@/api/order/customer';

// 表格实例
const eventsTableRef = ref(null);

// 表格列配置
const columns = ref([
  {
    key: 'index',
    width: 48,
    align: 'center',
    fixed: 'left',
    hideInSetting: true,
    customRender: ({ index }) => index + (eventsTableRef.value?.tableIndex ?? 0)
  },
  {
    title: '事件时间',
    dataIndex: 'eventDate',
    key: 'eventDate',
    // sorter: true
  },
  
  {
    title: '客户名称',
    dataIndex: 'customer',
    key: 'customer',
    // sorter: true
  },
  {
    title: '内容',
    dataIndex: 'content',
    key: 'content',
    // sorter: true
  },
  {
    title: '备注',
    dataIndex: 'remark',
    key: 'remark',
    // sorter: true
  },
  {
    title: '类型',
    dataIndex: 'type',
    key: 'type',
    // sorter: true
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
    resizable: true,
    width: 150,
    ellipsis: true,
    customRender: ({ text }) => toDateString(text)
  },
  {
    title: '创建人',
    dataIndex: 'createName',
    key: 'createName',
  },
  {
    title: '更新时间',
    dataIndex: 'updateTime',
    key: 'updateTime',
    resizable: true,
    width: 150,
    ellipsis: true,
    customRender: ({ text }) => toDateString(text)
  },
  {
    title: '更新人',
    dataIndex: 'updateName',
    key: 'updateName',
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
    align: 'center',
    fixed: 'right',
    hideInSetting: true
  }
]);

// 表单数据
const { form: eventsWhere, resetFields } = useFormData({
  username: '',
  sex: undefined
});

// 表格数据源
const datasource = ({ page, limit, where, orders }) => {
  return pageEvents({ ...where, ...orders, page, limit });
};

/* 搜索 */
const eventsReload = () => {
  eventsTableRef?.value?.reload({ page: 1, where: eventsWhere });
};
const eventsReload2 = () => {
  eventsTableRef?.value?.reload();
};

/*  重置 */
const eventsReset = () => {
  resetFields();
  eventsReload();
};

/* 删除单个 */
const eventsRemove = (record) => {
  const hide = message.loading('请求中..', 0);
  removeEvents(record.id).then((msg) => {
    hide();
    message.success(msg);
    eventsReload2();
  }).catch((e) => {
    hide();
    message.error(e.message);
  });
};

// 当前选中数据
const eventsCurrent = ref(null);

// 弹窗是否打开
const eventsVisible_modal = ref(false);

// 是否是修改
const eventsIsUpdate = ref(false);

// 提交状态
const loading = ref(false);

//
const eventsFormRef = ref(null);

// 表单数据
const { form: eventsForm, resetFields: eventsResetFormFields } = useFormData({
  id: undefined,
  customer: '',
  vessel: '',
});

// 表单验证规则
const eventsRules = reactive({
  eventDate: [
    {
      required: true,
      message: '请输入时间',
      type: 'string',
      trigger: 'blur'
    }
  ],
  content: [
    {
      required: true,
      message: '请输入内容',
      type: 'string',
    }
  ],
});

//防止重复刷新
//客户下拉列表
let customer_m_timeout = 0
const customerOptions = ref([]);
const customer_onSearch = searchText => {
  clearTimeout(customer_m_timeout)
  customer_m_timeout = setTimeout(() => {
    listCustomersSel({ 'name': searchText, type: '货代' }).then(msg => {
      customerOptions.value = msg
    }).catch((e) => {
    })
  }, TIME_OUT);
};
const customer_onSelect = (value2, option2) => {
  // let a = customerOptions.value.find((item)=> {return item.value=value})
  eventsForm.customer_val = option2.label
  eventsForm.customer = option2.label
  eventsForm.customerId = option2.value
};
const customer_blur = () => {
  eventsForm.customer_val = eventsForm.customer
};
const customer_onSelect_s = (value2, option2) => {
  // let a = customerOptions.value.find((item)=> {return item.value=value})
  eventsWhere.customer_val = option2.label
  eventsWhere.customer = option2.label
  eventsWhere.customerId = option2.value
};
const customer_blur_s = () => {
  // eventsWhere.customer_val = eventsWhere.customer
  eventsWhere.customer = eventsWhere.customer_val
};
// watch(() => eventsWhere.customer_val, (val) => {
//   eventsWhere.customer = eventsWhere.customer_val
// })

let where_timeout = 0
watch(() => eventsWhere, (val) => {
  clearTimeout(where_timeout)
  where_timeout = setTimeout(() => {
    eventsReload()
  }, TIME_OUT);
},
{ deep: true }
)
/* 打开编辑弹窗 */
const eventsOpenEdit = (record) => {
  eventsResetFormFields();
  eventsFormRef.value?.clearValidate();
  eventsCurrent.value = record?? {};
  eventsVisible_modal.value = true;
  Object.assign(eventsForm, record ?? {});
  eventsIsUpdate.value = !!record;
  if (record == undefined) {
    eventsForm.type = '报价'
  } 
};

/* 保存编辑 */
const eventsSave = () => {
  if (!eventsFormRef.value) {
    return;
  }
  eventsFormRef.value.validate().then(() => {
    loading.value = true;
    const saveOrUpdate = eventsIsUpdate.value ? updateEvents : addEvents;
    saveOrUpdate(eventsForm).then((msg) => {
      loading.value = false;
      message.success(msg);
      eventsVisible_modal.value = false;
      eventsReload2();
    }).catch((e) => {
      loading.value = false;
      message.error(e.message);
    });
  }).catch(() => {
  });
};
</script>

<script>
export default {
  name: 'DemoTest'
};
</script>

